import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,Avatar,message} from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
import { UserOutlined } from '@ant-design/icons';
import { matchScreen } from 'antd/es/_util/responsiveObserver';
const StudentHome = () =>{
    const [form] = useForm();
    const [data, setData] = useState([]);
    const [editedData, setEditedData] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [hovered, setHovered] = useState(false);
    useEffect(() => {
        const studentid = localStorage.getItem('studentid');
        //console.log(studentid);
        axios.get('http://localhost:8000/getstudenthome', { params: { studentid } })
          .then(response => {
            //console.log(response.data.list);
            setData(response.data.list);
            // 等待setData执行完毕后再打印data
            //console.log("Updated data:", data);
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      }, [editedData]);

      const change = () => {
        setIsModalVisible(true);
      }

      const handleOk = () => {
        const id =localStorage.getItem('studentid');
        const values = form.getFieldsValue(); // 获取表单修改后的值
        console.log('修改后的表单值:', values, id);
        console.log(values.oldpassword, data[0].password);
        if (values.oldpassword==data[0].password) {
        axios.post('http://localhost:8000/changestudentpassword', { id, values })
          .then(response => {
            // 处理来自后端的响应
            console.log('成功发送到后端并收到响应:', response.data);
            setIsModalVisible(false);
            message.success('密码修改成功');
          })
          .catch(error => {
            // 处理来自后端的任何错误
            console.error('与后端通信时发生错误:', error);
          });
        }else if (values.oldpassword!=data[0].password) {
            alert('旧密码输入错误')
        }
      };
      
    
      const handleCancel = () => {
        setIsModalVisible(false);
        //setEditedData([])
      };

      const changeAvatar = () => {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = 'image/*'; // 只允许选择图片文件
        fileInput.onchange = (e) => {
          const file = e.target.files[0];
          if (file) {
            // 执行上传逻辑
            uploadFileToServer(file);
          }
        };
        fileInput.click();
      };
      
      const uploadFileToServer = (file) => {
        const formData = new FormData();
        formData.append('file', file); // 使用 'file' 作为参数名
        formData.append('studentid', data[0].studentid);
        formData.append('avatar', data[0].avatar);
      
        fetch('http://localhost:8000/studentupload', {
          method: 'POST',
          body: formData
        })
        .then(response => {
          // 处理响应
          const studentid = localStorage.getItem('studentid');
          //console.log(studentid);
          axios.get('http://localhost:8000/getstudenthome', { params: { studentid } })
            .then(response => {
              //console.log(response.data.list);
              setData(response.data.list);
              // 等待setData执行完毕后再打印data
              //console.log("Updated data:", data);
              localStorage.setItem('avatar', response.data.list[0].avatar);
              window.location.reload();
            })
            .catch(error => {
              console.error('Error fetching data:', error);
            });
        })
        .catch(error => {
          // 处理错误
        });
      };
      
    return(
    <div style={{ height: '600px' }}>
    {data.length > 0 && (
      <div>
  <Space direction="vertical" size={16}>
    <Space wrap size={16}>
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <Avatar
        size={144}
        src={data[0].avatar ? `http://localhost:8000/${data[0].avatar}` : undefined}
        icon={!data[0].avatar && <UserOutlined />}
        onClick={changeAvatar}
        onMouseOver={() => setHovered(true)}
        onMouseOut={() => setHovered(false)}
      />
      {hovered && 
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', color: 'white', fontSize: '15px', backgroundColor: 'rgba(0, 0, 0, 0.7)', padding: '10px', textAlign: 'center' }}>
          点击修改头像
        </div>
      }
    </div>
    </Space>
  </Space>
        <h2>学生基本信息</h2>
        <p>姓名: {data[0].username}</p>
        <p>年级: {data[0].grade}</p>
        <p>班级: {data[0].class}</p>
        <p>专业: {data[0].major}</p>
        <p>学号: {data[0].studentid}</p>
        <Button type="link" onClick={change}>修改密码</Button>
      </div>
    )}

      <Modal
        title="修改密码"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        >
          {/* 这里添加表单字段，用于修改数据 */}
          <Form.Item label="旧密码" name="oldpassword" >
            <Input />
          </Form.Item>
          <Form.Item label="新密码" name="newpassword" >
            <Input />
          </Form.Item>
          {/* 添加其他表单字段... */}
        </Form>
      </Modal>
    </div>)
}

export default StudentHome